﻿using System.ServiceModel;
using System.Windows;
using Microsoft.Phone.Applications.Common;
using Microsoft.Phone.Controls;
using WP7AccelerometerClient.VirtualAccelerometerService;

namespace WP7AccelerometerClient
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private WP7AccelerometerServiceClient _wp7AccelerometerServiceClient;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // check whether the client started reporting data
            if (button.Content.ToString() == "Start")
            {
                // prepare wcf service address
                string address = string.Format("http://{0}:8192/WP7AccelerometerService", addressTextBox.Text);

                // create service client
                _wp7AccelerometerServiceClient = new WP7AccelerometerServiceClient(
                    new BasicHttpBinding(BasicHttpSecurityMode.None),
                    new EndpointAddress(address));

                // register for getting accelerometer data
                AccelerometerHelper.Instance.ReadingChanged += Instance_ReadingChanged;
                AccelerometerHelper.Instance.Active = true;

                button.Content = "Stop";
            }
            else
            {
                // stop getting accelerometer data
                AccelerometerHelper.Instance.Active = false;
                AccelerometerHelper.Instance.ReadingChanged -= Instance_ReadingChanged;

                // close wcf service client
                _wp7AccelerometerServiceClient.CloseAsync();
                
                button.Content = "Start";
            }
        }

        /// <summary>
        /// Called when new accelerometer data is available
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void Instance_ReadingChanged(object sender, AccelerometerHelperReadingEventArgs e)
        {
            // report new accelerometer data to wcf service
            _wp7AccelerometerServiceClient.ReportAccelerometerDataAsync((float)e.RawAcceleration.X, (float)e.RawAcceleration.Y, (float)e.RawAcceleration.Z);
        }
    }
}